<script setup lang="ts">
import { ref, onMounted,reactive, UnwrapRef, computed } from 'vue'
import { classesRecordList } from '../../stores/api/class'
import { useCounterStore } from '../../stores/counter'
import { useRoute, useRouter } from "vue-router";
import type { TableProps } from 'ant-design-vue';
import { ImgUrlPrefix } from '../../utils/config'
import VideoProgress from '../../components/VideoProgress.vue'
import { message } from 'ant-design-vue';
import { upload, videoUpload } from '../../utils/upload' // 引入js
import { start } from 'repl';
type Key = string | number;
const store = useCounterStore()
const router:any = useRouter()
const route:any = useRoute()
const loading:any = ref(false)
const data_list:any = ref([{id: 1, nick_name: '残花为谁悲'}])
const tabListNoTitle = [
  {
    key: 'record',
    tab: '上课记录',
  }
];
const noTitleKey = ref('record');
const pagination = reactive({
  total: 1,
  current: 1,
  pageSize: 15,
});
const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id'
  },
  {
    title: '课程名称/锁定时间',
    dataIndex: 'course',
    key: 'course',
  },
  // {
  //   title: '锁定时间',
  //   dataIndex: 'expire_time',
  //   key: 'expire_time',
  // },
  {
    title: '权限',
    dataIndex: 'permission',
    key: 'permission',
  },
  // {
  //   title: '昵称',
  //   dataIndex: 'nick_name',
  //   key: 'nick_name'
  // },
  {
    title: '学员账号/昵称',
    dataIndex: 'mobile',
    key: 'mobile'
  },
  {
    title: '头像',
    dataIndex: 'avatar',
    key: 'avatar',
  },
  {
    title: '观看分钟',
    dataIndex: 'view_count',
    key: 'view_count'
  }, 
   {
    title: '观看次数',
    dataIndex: 'visit_count',
    key: 'visit_count'
  }, 
  {
    title: '视频时长',
    dataIndex: 'video_time',
    key: 'video_time'
  },
  {
    title: '累计观看时长',
    dataIndex: 'view_time',
    key: 'view_time'
  },
  {
    title: '观看进度',
    dataIndex: 'visit_progress',
    key: 'visit_progress'
  }, 
  {
    title: '完成率',
    dataIndex: 'completion_rate',
    key: 'completion_rate'
  },
  {
    title: '创建时间',
    dataIndex: 'created_at',
    key: 'created_at',
  },
  {
    title: '更新时间',
    dataIndex: 'updated_at',
    key: 'updated_at',
  },
//   {
//     title: '操作',
//     key: 'action',
//     fixed: 'right',
//   },
];

const handleTableChange: TableProps['onChange'] = (
  pag: { pageSize: number; current: number }
) => {
  console.log(pag?.current)
  pagination.current = pag?.current
  getRecordList()
};

// 上课记录
const getRecordList = () => {
    loading.value = true
    classesRecordList({ page:  pagination.current, id: route.query.id }, 'post').then((res: any) => {
        console.log(res)
        if (res.code == 200) {
            data_list.value = res.data.items
            pagination.total = res.data.total
        }
        loading.value = false
    }).catch((err: any) => {
        console.log(err)
        loading.value = false
    })
}

const dataList = computed(() => {
  return data_list.value.map(item => {
       return { ...item, view_time:  item.times ? totalSeconds(item.times) : 0, video_time: item.course && item.course.video_time ? secondsToTime(item.course.video_time) : 0,completion_rate: completionRate(item.times, item.course && item.course.video_time ? item.course.video_time : 0) }
  })
})
// 转换为时分秒
const secondsToTime = (seconds) => {
  let hours:any = Math.floor(seconds / 3600);
  let minutes:any = Math.floor((seconds % 3600) / 60);
  let secs:any = seconds % 60;
  hours = hours < 10 ?  '0' + hours : hours
  minutes = minutes < 10 ?  '0' + minutes : minutes
  secs = secs < 10 ?  '0' + secs : secs
  return `${hours}:${minutes}:${secs}`;
}
// 获取累计观看时长
const totalSeconds =(events) => {
    let time = events.reduce((acc, event) => acc + (event.end - event.start), 0);
    console.log('secondsToTime(time)', secondsToTime(time))
    return secondsToTime(time)
}
// 观看完成率
const completionRate = (events, video_time) => {
    let time = 0
    let rate:any = 0
    if(events) {
        time = events.reduce((acc, event) => acc + (event.end - event.start), 0);
    }
    if(video_time) {
        console.log('sadasd', video_time)
       rate = Math.round((time / video_time) * 100) + '%'
    }
    return rate
}

const onTabChange = (value: string) => {
  console.log(value);
  noTitleKey.value = value;
  if(value == 'record') {
    getRecordList()
  }
}

// 图片地址拼接
const getImgUrl = (val) => {
    const url = ImgUrlPrefix(val)
    return url
}
const imgUrl = (val) => {
    if(val == 'def-avatar.png') {
        return new URL(`../../assets/${val}`, import.meta.url).href
    } else {
        return val
    }
}
onMounted(() => {
    getRecordList()
})
</script>

<template>
    <div class="classRecord">
        <a-page-header
            style="border: none;padding: 0"
            title="上课记录"
            sub-title=""
            @back="() => $router.go(-1)"
        />
        <a-card
            style="width: 100%"
            :tab-list="tabListNoTitle"
            :active-tab-key="noTitleKey"
            @tabChange="key => onTabChange(key)"
        >
            <div v-if="noTitleKey === 'record'">
                <div class="list-box">
                    <a-table :columns="columns" :pagination="pagination"
                        :loading="loading" :data-source="dataList" @change="handleTableChange">
                        <template #bodyCell="{ column, record }">
                            <template v-if="column.key === 'id'">
                                <span>
                                    {{ record.id }}
                                </span>
                            </template>
                            <template v-if="column.key === 'course'">
                                <div>
                                   {{ record.course && record.course.title ? record.course.title : '--' }}
                                </div>
                                <div style="color: #87d068">
                                   {{ record.course && record.course.expire_time ? store.timestampChangDate(record.course.expire_time * 1000) : '' }}
                                </div>
                            </template>
                            <!-- <template v-if="column.key === 'expire_time'">
                                <span>
                                {{  record.course && record.course.expire_time ? store.timestampChangDate(record.course.expire_time * 1000) : '--' }}
                                </span>
                            </template> -->
                            <template v-else-if="column.key === 'permission'">
                                <span>
                                    <a-tag color="green" v-if="record.course && record.course.permission == 10">所有人</a-tag>
                                    <a-tag color="cyan" v-else-if="record.course && record.course.permission == 20">会员</a-tag>
                                    <span v-else>--</span>
                                </span>
                            </template>
                            <!-- <template v-if="column.key === 'nick_name'">
                                <span>
                                {{ record.user && record.user.nick_name ? record.user.nick_name : '-' }}
                                </span>
                            </template> -->
                            <template v-if="column.key === 'mobile'">
                                <div>
                                   {{ record.user && record.user.mobile ? record.user.mobile : '-' }}
                                </div>
                                <div style="color: #87d068">
                                   {{ record.user && record.user.nick_name ? record.user.nick_name : '-' }}
                                </div>
                            </template>
                            <template v-else-if="column.key === 'avatar'">
                                <span>
                                    <img :src="record.user && record.user.avatar && record.user.avatar == 'def-avatar.png' ? imgUrl(record.user.avatar) : record.user && record.user.avatar &&  record.user.avatar != 'def-avatar.png' ? getImgUrl(record.user.avatar) : ''" alt="" class="thumbnail_">
                                </span>
                            </template>
                            <template v-if="column.key === 'visit_count'">
                                <span>
                                {{ record.visit_count ? record.visit_count : '0' }}
                                </span>
                            </template>
                            <template v-if="column.key === 'view_count'">
                                <span>
                                {{ record.view_count ? record.view_count +'分钟' : '0' }}
                                </span>
                            </template>
                            <template v-if="column.key === 'video_time'">
                                <span>
                                {{ record.video_time ? record.video_time : '0' }}
                                </span>
                            </template>
                            <template v-if="column.key === 'view_time'">
                                <span>
                                {{ record.view_time ? record.view_time : '0' }}
                                </span>
                            </template>
                            <template v-if="column.key === 'visit_progress'">
                                <span>
                                    <!-- 进度展示组件 videoTotalTime // 总时长（秒） 1小时 videoWatchedTime // 已观看时长（秒） 15分钟[{start: 0, end: 60}, {start: 60, end: 120}, {start: 125, end: 185}, {start: 175, end: 235}]--> 
                                    <VideoProgress 
                                    :total-time="record.course && record.course.video_time ? record.course.video_time : 0" 
                                    :watched-time="900"
                                    :watched-time-quantum="record.times ? record.times : []"
                                    />
                                <!-- {{ record.view_count ? record.view_count +'分钟' : '0' }} -->
                                </span>
                            </template>
                            <template v-if="column.key === 'completion_rate'">
                                <span>
                                {{ record.completion_rate ? record.completion_rate : '0' }}
                                </span>
                            </template>
                            <template v-if="column.key === 'status'">
                                <span>
                                {{ record.status > 100000000 ? store.timestampChangDate(record.status * 1000) : '--'  }}
                                </span>
                            </template>
                            <template v-if="column.key === 'created_at'">
                                <span>
                                {{ store.timestampChangDate(record.created_at * 1000) || '--' }}
                                </span>
                            </template>
                            <template v-if="column.key === 'updated_at'">
                                <span>
                                {{ store.timestampChangDate(record.updated_at * 1000) || '--' }}
                                </span>
                            </template>
                            <!-- <template v-else-if="column.key === 'action'"> -->
                                <!-- <span style="margin-right: 10px">
                                    <a @click="handleUpdate(record)">编辑</a>
                                </span>
                                <span style="margin-right: 10px">
                                    <a-popconfirm title="是否删除吗？" ok-text="确定" cancel-text="取消" @confirm="handleDelete(record.id)"> 
                                        <template #icon><question-circle-outlined style="color: red" /></template>
                                        <a>删除</a>
                                    </a-popconfirm>
                                </span> -->
                            <!-- </template> -->
                        </template>
                    </a-table>
                </div>
            </div>
            <!-- <template #tabBarExtraContent>
                <a @click="handleAdd" >添加</a>
            </template> -->
        </a-card>
    </div>
</template>

<style scoped>
.classRecord{
    padding: 15px;
}
.thumbnail_{
    width: 50px;
    height: 50px;
    border-radius: 50%;
    object-fit: cover;
}
</style>